import {commonLang} from '@inbiz/utils'
import moment from 'moment';
import { ConfigProvider, DatePicker } from 'antd';
import {
  createInbizSchema,
  createBaseSchema,
  createValidatorSchema,
  createComponentStyleSchema,
  createDecoratorStyleSchema,
  createModelSchema,
  getDefalutDecoratorProps,
  createComponentLayout,
  createControllerSchema,
} from '@inbiz/setters';
import { createBehavior, createResource, GlobalRegistry } from '@inbiz/core';
import { getMessage } from '@inbiz/react';
import { getPlatform } from '@inbiz/utils';
import { EformDatePicker } from './locale';
import '../preview/web/style.less';

export const defaultProps = {
  format: 'YYYY-MM-DD',
  defaultValueType: 'variableDefaultValue',
  customDefaultValue: null,
  variableDefaultValue: 'nowTime',
  placeholder: 'EformDatePicker.placeholder',
  allowBeforeNow: true,
  allowClear: true,
  min: '',
  max: '',
};

export const propsSchema = createInbizSchema({
  attribute: {
    ...createBaseSchema({
      selectTitle: {
        type: 'string',
        'x-decorator': 'FormItem',
        'x-component': 'Input',
        platform: 'wap',
      },
      format: {
        type: 'string',
        enum: [
          'YYYY',
          'YYYYMMDD',
          'YYYY-MM',
          'YYYY-MM-DD',
          'YYYY-MM-DD HH:mm',
          'YYYY-MM-DD HH:mm:ss',
          'YYYY/MM/DD',
          'YYYY/MM/DD HH:mm',
          'YYYY/MM/DD HH:mm:ss',
          'DD-MM-YYYY',
          'DD-MM-YYYY HH:mm',
          'DD-MM-YYYY HH:mm:ss',
          'DD/MM/YYYY',
          'DD/MM/YYYY HH:mm',
          'DD/MM/YYYY HH:mm:ss',
        ],
        'x-decorator': 'FormItem',
        'x-component': 'Select',
      },
      defaultValueType: {
        type: 'string',
        enum: ['variableDefaultValue', 'customDefaultValue'],
        'x-decorator': 'FormItem',
        'x-component': 'Radio.Group',
      },
      customDefaultValue: {
        type: 'date',
        'x-decorator': 'FormItem',
        'x-component-props': {
          format: defaultProps.format,
        },
        'x-component': (props: any) => {
          const format = props.format;
          const locale=commonLang[GlobalRegistry.getDesignerLanguage() as keyof typeof commonLang]
          return (
            <ConfigProvider locale={locale}>
              <DatePicker
                {...props}
                dropdownClassName="clearSpaceOccupation"
                inputReadOnly={true}
                value={props.value ? moment(props.value) : props.value}
                showTime={
                  format?.indexOf('s') != -1 ||
                    format?.indexOf('m') != -1 ||
                    format?.indexOf('H') != -1
                    ? { format: format?.split(' ')[1] }
                    : false
                }
                picker={format === 'YYYY' ? 'year' : format?.indexOf('D') != -1 ? 'date' : 'month'}
                placeholder={getMessage('EformDatePicker.pleaseChoseDefualt')}
              />
            </ConfigProvider>
          );
        },
        'x-reactions': {
          dependencies: ['.defaultValueType', '.format'],
          fulfill: {
            schema: {
              'x-hidden': "{{$deps[0] !== 'customDefaultValue'}}",
              'x-component-props.format': '{{$deps[1]}}',
            },
          },
        },
      },
      variableDefaultValue: {
        type: 'string',
        enum: ['nowTime'],
        'x-decorator': 'FormItem',
        'x-component': 'Select',
        'x-reactions': {
          dependencies: ['.defaultValueType'],
          fulfill: {
            schema: {
              'x-hidden': "{{$deps[0] !== 'variableDefaultValue'}}",
            },
          },
        },
      },
      placeholder: {
        type: 'string',
        'x-decorator': 'FormItem',
        'x-component': 'MultilingualInput',
      },
      allowBeforeNow: {
        type: 'boolean',
        'x-decorator': 'FormItem',
        'x-component': 'Switch',
      },
      allowClear: {
        type: 'boolean',
        'x-decorator': 'FormItem',
        'x-component': 'Switch',
        platform: 'web',
      },
    }),
    ...createValidatorSchema(false, {
      'x-component-props': {
        type: 'object',
        properties: {
          min: {
            type: 'date',
            'x-decorator': 'FormItem',
            'x-component-props': {
              format: defaultProps.format,
            },
            'x-component': (props: any) => {
              const format = props.format;
              const onChange = (value: any) => {
                var formatValue = value;
                if (value) {
                  if (format?.indexOf('s') != -1) {
                    formatValue = moment(value).startOf('second');
                  } else if (format?.indexOf('m') != -1) {
                    formatValue = moment(value).startOf('minute');
                  } else if (format?.indexOf('H') != -1) {
                    formatValue = moment(value).startOf('hour');
                  } else if (format?.indexOf('D') != -1) {
                    formatValue = moment(value).startOf('day');
                  } else if (format?.indexOf('M') != -1) {
                    formatValue = moment(value).startOf('month');
                  } else {
                    formatValue = moment(value).startOf('year');
                  }
                }
                props.onChange(formatValue);
              };
              // 控制最小值不能大于最大值（移除焦点，大于最大值，清空最小值）
              const handleBlur = () => {
                // 是否大于最大值
                const max = props.max;
                if (max && moment(props.value) > moment(max)) {
                  props.onChange(null);
                }
              };
              const locale=commonLang[GlobalRegistry.getDesignerLanguage() as keyof typeof commonLang]
              return (
                <ConfigProvider locale={locale}>
                  <DatePicker
                    {...props}
                    dropdownClassName="clearSpaceOccupation"
                    inputReadOnly={true}
                    placeholder={getMessage('EformDatePicker.pleaseChoseDate')}
                    value={props.value ? moment(props.value) : props.value}
                    onChange={onChange}
                    showTime={
                      format?.indexOf('s') != -1 ||
                        format?.indexOf('m') != -1 ||
                        format?.indexOf('H') != -1
                        ? { format: format?.split(' ')[1] }
                        : false
                    }
                    picker={
                      format === 'YYYY' ? 'year' : format?.indexOf('D') != -1 ? 'date' : 'month'
                    }
                    onBlur={handleBlur}
                  />
                </ConfigProvider>
              );
            },
            'x-reactions': {
              dependencies: ['.format', '.max'],
              fulfill: {
                schema: {
                  'x-component-props.format': '{{$deps[0]}}',
                  'x-component-props.max': '{{$deps[1]}}',
                },
              },
            },
          },
          max: {
            type: 'date',
            'x-decorator': 'FormItem',
            'x-component-props': {
              format: defaultProps.format,
            },
            'x-component': (props: any) => {
              const format = props.format;
              const onChange = (value: any) => {
                var formatValue = value;
                if (value) {
                  if (format?.indexOf('s') != -1) {
                    formatValue = moment(value).endOf('second');
                  } else if (format?.indexOf('m') != -1) {
                    formatValue = moment(value).endOf('minute');
                  } else if (format?.indexOf('H') != -1) {
                    formatValue = moment(value).endOf('hour');
                  } else if (format?.indexOf('D') != -1) {
                    formatValue = moment(value).endOf('day');
                  } else if (format?.indexOf('M') != -1) {
                    formatValue = moment(value).endOf('month');
                  } else {
                    formatValue = moment(value).endOf('year');
                  }
                }
                props.onChange(formatValue);
              };
              // 控制最大值不能小于最小值（移除焦点，小于最小值，清空最大值）
              const handleBlur = () => {
                const min = props.min;
                if (min && moment(props.value) < moment(min)) {
                  props.onChange(null);
                }
              };
              const locale=commonLang[GlobalRegistry.getDesignerLanguage() as keyof typeof commonLang]
              return (
                <ConfigProvider locale={locale}>
                  <DatePicker
                    {...props}
                    dropdownClassName="clearSpaceOccupation"
                    inputReadOnly={true}
                    placeholder={getMessage('EformDatePicker.pleaseChoseDate')}
                    value={props.value ? moment(props.value) : props.value}
                    onChange={onChange}
                    showTime={
                      format?.indexOf('s') != -1 ||
                        format?.indexOf('m') != -1 ||
                        format?.indexOf('H') != -1
                        ? { format: format?.split(' ')[1] }
                        : false
                    }
                    picker={
                      format === 'YYYY' ? 'year' : format?.indexOf('D') != -1 ? 'date' : 'month'
                    }
                    onBlur={handleBlur}
                  />
                </ConfigProvider>
              );
            },
            'x-reactions': {
              dependencies: ['.min', '.format'],
              fulfill: {
                schema: {
                  'x-component-props.min': '{{$deps[0]}}',
                  'x-component-props.format': '{{$deps[1]}}',
                },
              },
            },
          },
        },
      },
    }),
  },
  style: {
    ...createComponentStyleSchema(),
    ...createComponentLayout(),
    ...createDecoratorStyleSchema(),
  },
  senior: {
    ...createModelSchema(),
    // ...createSoureSchema(),
  },
  controller: createControllerSchema({
    events: [{
      name:'onChange',
      label:'数据变更'
    },
    {
      name:'onOk',
      label:'确定',
      platform:'web'
    },
    {
      name:'onOpenChange',
      label:'弹出/关闭日历',
      platform:'web'
    }
  ]
  })
});

export const Behavior = createBehavior({
  name: 'EformDatePicker',
  extends: ['Field'],
  selector: (node) => node.props?.['x-component'] === 'EformDatePicker',
  designerLocales: EformDatePicker,
  designerProps: { propsSchema },
});

export const Resource = createResource({
  icon: 'SingleTime',
  elements: [
    {
      componentName: 'Field',
      props: {
        type: 'string',
        title: {
          value: 'EformDatePicker.title',
          status: true,
        },
        'x-decorator': 'FormItem',
        'x-component': 'EformDatePicker',
        'x-component-props': defaultProps,
        'x-decorator-props': getDefalutDecoratorProps(getPlatform()),
      },
    },
  ],
});
